编程之美 3.8

//以下是递归算法

#include "stdafx.h"
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<assert.h>
#include<vector>
#include<fstream>
#include<queue>
using namespace std;

struct Tree
{
 Tree(char value)
   {
    pLeft=pRight=NULL;
 this->value=value;
 //distance=depth=0;
   }
 Tree *pLeft,*pRight;
 char value;
 //int distance;
 //int depth;
};
void CreateTree(Tree *&T,int &index)
{// 以# 代替空
// A B D H # # # E # # C F # I # #  G # #
//A B D F H # # # G # I # # E # # C # #
    ifstream in;
 in.open("Tree.txt");
 in.seekg(index*2);
 index++;
 char value;
 in>>value;
 //std::cout<<value<<" ";
 if(value=='#')
  T=NULL;
 else
 {
  T=new Tree(value);
  CreateTree(T->pLeft,index);
  CreateTree(T->pRight,index);
  

 }
  

    in.clear();
 in.close();
 
}
void DestroyTree(struct Tree*&T)
{
 if(T)
 {
  DestroyTree(T->pLeft);
  DestroyTree(T->pRight);
  delete T;
 }
}
void LevelOrderTraverse(struct Tree*&T)
{
 std::cout<<std::endl<<"----------------------中序遍历二叉树结构------------------"<<std::endl;
 std::queue<Tree*>Q;
 Q.push(T);
 while(!Q.empty())
 {
  Tree *tempT=Q.front();
  Q.pop();
  if(tempT)
  {
   std::cout<<tempT->value<<"  ";
   Q.push(tempT->pLeft);
   Q.push(tempT->pRight);
  }
  else
  {
   std::cout<<"#"<<"  ";
  }
 }
 std::cout<<std::endl<<"-----------------------------------------------------------"<<std::endl;

}
void ComputeMaxDistance(Tree* &T,int &dis,int&depth)
{
      dis=0;
      depth=0;
  if(T)
  {
  int rDis=0,lDis=0,lDepth=0,rDepth=0;
   ComputeMaxDistance(T->pLeft,lDis,lDepth);
   ComputeMaxDistance(T->pRight,rDis,rDepth);
      depth=max(lDepth,rDepth)+1;
   dis=max(2+rDepth+lDepth,max(lDis,rDis));
  
  }
  else
  {
   depth=-1;

  }
}
void RunAlgorithm()
{
 Tree *T;int index=0;
 CreateTree(T,index);
 LevelOrderTraverse(T);
    int maxDepth,maxDis;
 ComputeMaxDistance(T,maxDis,maxDepth);
 std::cout<<"maxDis:"<<maxDis<<"  maxDepth:"<<maxDepth<<std::endl;
 DestroyTree(T);
 
}

//以下主函数
int _tmain(int argc, _TCHAR* argv[])
{
 
    RunAlgorithm();
   
 system("pause");

 return 0;
}

 

扩展问题:

非递归算法就是后续遍历的非递归算法而已

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值